/**
 * elancom Corporation copy right 2012 - 2015  
 *   
 * $Header: https://192.168.1.224/svn/elancom/product/elancom-platform/trunk/src/main/java/com/elancom/framework/commons/json/parser/deserializer/ListResolveFieldDeserializer.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Id: ListResolveFieldDeserializer.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Author: lanzhouxue $
 * $Date: 2012-07-02 11:09:12 +0800 (Mon, 02 Jul 2012) $
 * $Revision: 1034 $
 */
package com.elancom.framework.commons.json.parser.deserializer;

import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

import com.elancom.framework.commons.json.JSONArray;
import com.elancom.framework.commons.json.parser.DefaultJSONParser;
import com.elancom.framework.commons.json.util.TypeUtils;

@SuppressWarnings("rawtypes")
public final class ListResolveFieldDeserializer extends FieldDeserializer {

	private final int index;
	private final List list;
	private final DefaultJSONParser parser;

	public ListResolveFieldDeserializer(DefaultJSONParser parser, List list, int index) {
		super(null, null);
		this.parser = parser;
		this.index = index;
		this.list = list;
	}

	@Override
	@SuppressWarnings("unchecked")
	public void setValue(Object object, Object value) {
		list.set(index, value);

		if (list instanceof JSONArray) {
			final JSONArray jsonArray = (JSONArray) list;
			final Object array = jsonArray.getRelatedArray();

			if (array != null) {
				final int arrayLength = Array.getLength(array);

				if (arrayLength > index) {
					Object item;
					if (jsonArray.getComponentType() != null) {
						item = TypeUtils.cast(value, jsonArray.getComponentType(), parser.getConfig());
					} else {
						item = value;
					}
					Array.set(array, index, item);
				}
			}
		}
	}

	public DefaultJSONParser getParser() {
		return parser;
	}

	@Override
	public void parseField(DefaultJSONParser parser, Object object, Type objectType, Map<String, Object> fieldValues) {

	}

	@Override
	public int getFastMatchToken() {
		return 0;
	}
}
